<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="/pages/inc/taglibs.jsp"%>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>工时填报</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/js/third/validator/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" />
<script type="text/javascript"
		src="<%=request.getContextPath()%>/js/third/validator/jquery.validationEngine-zh_CN.js"></script>
<script type="text/javascript"
	src="<%=request.getContextPath()%>/js/third/validator/jquery.validationEngine.min.js"></script>
</head>
<body class="body">
	
  <div class="container dashboard">
	  <div class="container filter"> 
			<div>
				<label id="weekNumber"></label>
				<button type="button" id="btnPreWeek" class="btn btn-default btn-sm">
		          <span class="glyphicon glyphicon-chevron-up"></span>上一周
		        </button>
		        <button type="button" id="btnNextWeek" class="btn btn-default btn-sm">
		          <span class="glyphicon glyphicon-chevron-down"></span>下一周
		        </button>
				<button style="float: right;margin-bottom:10px;" class="btn btn-default" id="btnSubmit">保存并提交</button>
			</div>
			<div>
				<form id="timeSheetForm" action="" method="post">
					<input type="hidden" id="startDate" name="startDate" value="" />
					<input type="hidden" id="endDate" name="endDate" value="" />
					<input type="hidden" id="projectId" name="projectId" value="" />
					<input type="hidden" id="projectWbs" name="projectWbs" value="" />
					<input type="hidden" id="nowDate" value="" />
					<table id="timeSheetTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
						<thead>
							<tr>
								<th>项目</th>
								<th>WBS</th>
								<th>周一</th>
								<th>周二</th>
								<th>周三</th>
								<th>周四</th>
								<th>周五</th>
								<th style="color: #FF0000">周六</th>
								<th style="color: #FF0000">周日</th>
							</tr>
						</thead>
						<tbody id="timeSheetBody"></tbody>
					</table>
				</form>
				<button id="btnAddRow" onclick="addRow();">+</button>
			</div>
		</div>
	</div>

	<script type="text/javascript">
		var date = new Date("${nowDate}");
		$("#nowDate").val("${nowDate}");
		var holidays = "${holidays}";
		var workdays = "${workdays}";

		$(document).ready(
				function() {

					initCurrentWeekLabel(date);
					initTimeSheetTableBody();

					$("#btnPreWeek").click(function(){
						initCurrentWeekLabel(new Date(addDate($("#startDate").val(), -7)));
						initTimeSheetTableBody();
						$("#btnSubmit").attr("disabled", false);
						$("#btnAddRow").attr("disabled", false);
					});

					$("#btnNextWeek").click(function(){
						initCurrentWeekLabel(new Date(addDate($("#startDate").val(), 7)));
						initTimeSheetTableBody();
						$("#btnSubmit").attr("disabled", false);
						$("#btnAddRow").attr("disabled", false);
					});

					$("#btnSubmit").click(function(){
						
						var timesheets = new Array();
						var validMsg;
						$("#timeSheetBody").find("tr").each(function(i){

							if ($(this).find("select[name='project']").val() == "0" 
								|| $(this).find("select[name='wbs']").val() == "0") {
								validMsg = "请选择项目名称或者 WBS";
								return;
							}
							var timesheet = {};
							timesheet.startDate = $("#startDate").val();
							timesheet.endDate = $("#endDate").val();
							timesheet.projectId = $(this).find("select[name='project']").val();
							timesheet.projectWbs = $(this).find("select[name='wbs']").val();
							timesheet.firstDay = $(this).find("input[name='firstDay']").val();
							timesheet.secondDay = $(this).find("input[name='secondDay']").val();
							timesheet.thirdDay = $(this).find("input[name='thirdDay']").val();
							timesheet.fourthDay = $(this).find("input[name='fourthDay']").val();
							timesheet.fifthDay = $(this).find("input[name='fifthDay']").val();
							timesheet.sixthDay = $(this).find("input[name='sixthDay']").val();
							timesheet.seventhDay = $(this).find("input[name='seventhDay']").val();
							timesheets.push(timesheet);
						});

						if (validMsg && validMsg.length > 0) {
							alert(validMsg);
							return;
						}

						$.ajax({
							url : "<c-rt:url value='/timesheet/save' />",
							type : 'POST',
							data : {"timesheetJson":JSON.stringify(timesheets)},
							dataType : "text",
							success : function(data) {
								if (data && data.length > 0) {
									alert(data);
								} else {
									initCurrentWeekLabel(new Date(addDate($("#startDate").val(), 7)));
									initTimeSheetTableBody();
								}
							}
						});
					});

					/*
					$('#timeSheetForm').validationEngine({
							ajaxFormValidation: true,
						    ajaxFormValidationMethod: 'post',
						    onAjaxFormComplete: ajaxValidationCallback,
						    onBeforeAjaxFormValidation: beforeCall
						});
					*/
				});

		
		function beforeCall(form, options) {

			return true;
		}

		function ajaxValidationCallback(status, form, json, options) {

			if (status === true) {
				initCurrentWeekLabel(new Date(addDate(date, 7)));
				initTimeSheetTableBody();
			}
		}

		function initCurrentWeekLabel(date) {
			var weekNumber = getWeekNumber(date.getYear(), date.getMonth(),
					date.getDate());
			$("#startDate").val(getStartOfCurrentWeek(date));
			$("#endDate").val(getEndOfCurrentWeek(date));

			$("#weekNumber").html(
					"第" + weekNumber + "周," + $("#startDate").val() + " - "
							+ $("#endDate").val());
		}

		function initNextWeekLabel(date) {
			var weekNumber = getWeekNumber(date.getYear(), date.getMonth(),
					date.getDate());

			$("#startDate").val(getStartOfCurrentWeek(date));
			$("#endDate").val(getEndOfCurrentWeek(date));

			$("#weekNumber").html(
					"第" + weekNumber + "周," + $("#startDate").val() + " - "
							+ $("#endDate").val());
		}

		function initTimeSheetTableBody() {

			$("#timeSheetBody").html("");
			var jsonData = {};
			jsonData.startDate = $("#startDate").val();
			jsonData.endDate = $("#endDate").val();
			$.ajax({
					url : "<c-rt:url value='/timesheet/specialWeekTimesheet' />",
					type : 'POST',
					data : jsonData,
					dataType : "json",
					success : function(data) {
						if (data && data.length > 0) {
							$(data).each(function(i, timesheet){
	
									$("#btnSubmit").attr("disabled", "true");
									$("#btnAddRow").attr("disabled", "true");
									
									$("#timeSheetBody").append("<tr style='margin-top:2px;'></tr>");
									var row = $("#timeSheetBody").find("tr").eq(i);
									
									row.append("<td>" + timesheet.projectId + "</td>");
									row.append("<td>" + timesheet.projectWbs + "</td>");
			
									appendTd(row, timesheet.firstDay == null ? 0 : timesheet.firstDay, "firstDay", 0) ;
									
									appendTd(row, timesheet.secondDay == null ? 0 : timesheet.secondDay, "secondDay", 1) ;
			
									appendTd(row, timesheet.thirdDay == null ? 0 : timesheet.thirdDay, "thirdDay", 2) ;
			
									appendTd(row, timesheet.fourthDay == null ? 0 : timesheet.fourthDay, "fourthDay", 3) ;
			
									appendTd(row, timesheet.fifthDay == null ? 0 : timesheet.fifthDay, "fifthDay", 4) ;
			
									appendTd(row, timesheet.sixthDay == null ? 0 : timesheet.sixthDay, "sixthDay", 5) ;
			
									appendTd(row, timesheet.seventhDay == null ? 0 : timesheet.seventhDay, "seventhDay", 6) ;
								});
						} else {
							$("#timeSheetBody").append("<tr style='margin-top:2px;'></tr>");
							var row = $("#timeSheetBody").find("tr").first();
							row.append("<td><select name='project' class='validate[required]' onchange='loadWPS(this);'><option value='0'>--请选择项目--</option></select></td>");
							var td = row.find("select[name='project']");

							<c-rt:forEach items="${projects}" var="project">
								td.append("<option value='${project.id}'>${project.projectName}</option>");
							</c-rt:forEach>

							row.append("<td><select id='wbs' name='wbs' class='validate[required]'><option value='0'>--请选择 WBS--</option></select></td>");

							appendTd(row, 0, "firstDay", 0) ;
							
							appendTd(row, 0, "secondDay", 1) ;

							appendTd(row, 0, "thirdDay", 2) ;

							appendTd(row, 0, "fourthDay", 3) ;

							appendTd(row, 0, "fifthDay", 4) ;

							appendTd(row, 0, "sixthDay", 5) ;

							appendTd(row, 0, "seventhDay", 6) ;
						}

					}
				});
		}

		function addRow() {
			
			var date = new Date($("#nowDate").val());
		
			var fRow = $("#timeSheetBody").find("tr").first();
			var proOptions = fRow.find("td").first().find("select").html();
			
			$("#timeSheetBody").append("<tr style='margin-top:2px;'></tr>");
			var row = $("#timeSheetBody").find("tr").last();
		
			row.append("<td><select class='validate[required]' name='project' onchange='loadWPS(this);'><option value='0'>-- 请选择项目 --</option></select></td>");
			var proSelect = row.find("td").first().find("select");	
			proSelect.html(proOptions);
			
			row.append("<td><select id='wbs' class='validate[required]' name='wbs'><option value='0'>-- 请选择WBS --</option></select></td>");

			appendTd(row, 0, "firstDay", 0) ;
			
			appendTd(row, 0, "secondDay", 1) ;

			appendTd(row, 0, "thirdDay", 2) ;

			appendTd(row, 0, "fourthDay", 3) ;

			appendTd(row, 0, "fifthDay", 4) ;

			appendTd(row, 0, "sixthDay", 5) ;

			appendTd(row, 0, "seventhDay", 6) ;
			
		}

		function appendTd(row, weekDay, weekDayStr, day) {
			var firstDay = $("startDate").val();
			if (day <= 4) {
				if (weekDay && weekDay > 0) {
					row.append("<td>" + weekDay
							+ "</td>");
				} else {
					if (holidays.indexOf(getSpecialDayOfCurrentWeek(
									firstDay, day)) > -1) {
						row.append("<td><input class='form-control' type='text' name='" + weekDayStr + "' disabled='disabled'/></td>");
					} else {
						row.append("<td><input class='form-control validate[custom[integer], max[8]]' type='text' name='" + weekDayStr + "' title='请填写工时' /></td>");
					}
				}
			} else {
				if (weekDay && weekDay > 0) {
					row.append("<td>" + weekDay + "</td>");
				} else {
					var workday ;
					if (day == 5) {
						workday = getSaturdayOfCurrentWeek(new Date($("sysDate").val()));
					} else {
						workday = getEndOfCurrentWeek(new Date($("sysDate").val()));
					}
					if (workdays.indexOf(workday) > -1) {
						row.append("<td><input class='form-control' name='" + weekDayStr + "' class='form-control' /></td>");
					} else {
						row.append("<td><input class='form-control validate[custom[integer], max[8]]' type='text' name='" + weekDayStr + "' class='form-control' disabled='disabled' /></td>");
					}
				}
			}
		}

		function loadWPS(obj) {
			var projectId = $(obj).val();
			$.ajax({
				url : "<c-rt:url value='/timesheet/loadWps' />",
				data : {
					projectId : projectId
				},
				type : 'POST',
				dataType : "json",
				success : function(data) {
					var td = $(obj).parent().parent().find("td").eq(1).find("select");
					$.each(data, function(i, wps) {
						td.append("<option value='" + wps.id + "'>"
								+ wps.wbsName + "</option>");
					});
				}
			});
		}

		function formatDate(date) {
			var myyear = date.getFullYear();
			var mymonth = date.getMonth() + 1;
			var myweekday = date.getDate();

			if (mymonth < 10) {
				mymonth = "0" + mymonth;
			}
			if (myweekday < 10) {
				myweekday = "0" + myweekday;
			}
			return (myyear + "-" + mymonth + "-" + myweekday);
		}

		function getStartOfCurrentWeek(date) {
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekStartDate = new Date(year, month, day - dayOfWeek + 1);
			return formatDate(weekStartDate);
		}

		function getStartOfNextWeek(date) {
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekStartDate = new Date(year, month, day - dayOfWeek + 8);
			return formatDate(weekStartDate);
		}

		function getSpecialDayOfCurrentWeek(firstDay, n) {
			//var firstDay = firstDay.replace('-', '/');
			var date = new Date(firstDay);

			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekStartDate = new Date(year, month, day + (7 - dayOfWeek - n));
			return formatDate(weekStartDate);
		}

		function getEndOfCurrentWeek(date) {
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekEndDate = new Date(year, month, day + (7 - dayOfWeek));
			return formatDate(weekEndDate);
		}

		function getEndOfNextWeek(date) {
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekEndDate = new Date(year, month, day + 7 + (7 - dayOfWeek));
			return formatDate(weekEndDate);
		}

		function getSaturdayOfCurrentWeek(date) {
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var dayOfWeek = date.getDay();
			var weekEndDate = new Date(year, month, day + (6 - dayOfWeek));
			return formatDate(weekEndDate);
		}

		/**
		 * 判断年份是否为润年
		 *
		 * @param {Number} year
		 */
		function isLeapYear(year) {
			return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
		}

		/**
		 * 获取某一年份的某一月份的天数
		 *
		 * @param {Number} year
		 * @param {Number} month
		 */
		function getMonthDays(year, month) {
			return [ 31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ][month]
					|| (isLeapYear(year) ? 29 : 28);
		}

		/**
		 * 获取某年的某天是第几周
		 * @param {Number} y
		 * @param {Number} m
		 * @param {Number} d
		 * @returns {Number}
		 */
		function getWeekNumber(y, m, d) {
			var now = new Date(y, m - 1, d), year = now.getFullYear(), month = now
					.getMonth(), days = now.getDate();
			//那一天是那一年中的第多少天
			for (var i = 0; i < month; i++) {
				days += getMonthDays(year, i);
			}

			//那一年第一天是星期几
			var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

			var week = null;
			if (yearFirstDay == 1) {
				week = Math.ceil(days / yearFirstDay);
			} else {
				days -= (7 - yearFirstDay + 1);
				week = Math.ceil(days / 7) + 1;
			}
			return week;
		}

		function addDate(date, days) {
			if (days == undefined || days == '') {
				days = 1;
			}
			var newDate = new Date(date);
			newDate.setDate(newDate.getDate() + days);
			return formatDate(newDate);
		}
	</script>
</body>


</html>